package com.ruoyi.common.config.serializer;

import java.io.IOException;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.StreamSupport;

import org.springframework.util.StringUtils;

import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.TreeNode;
import com.fasterxml.jackson.databind.DeserializationContext;
import com.fasterxml.jackson.databind.JsonDeserializer;
import com.fasterxml.jackson.databind.JsonSerializer;
import com.fasterxml.jackson.databind.SerializerProvider;
import com.fasterxml.jackson.databind.node.ArrayNode;

public class JsonSerializers {

    public static final class StringToArraySerialize extends JsonSerializer<String> {

        @Override
        public void serialize(String value, JsonGenerator gen, SerializerProvider serializers) throws IOException {
            if (StringUtils.hasText(value)) {
                final String[] strings = value.replaceAll("\"", "").split(",");
                gen.writeArray(strings, 0, strings.length);
            } else {
                gen.writeObject(List.of());
            }
        }

    }

    public static final class ArrayToStringDeSerialize extends JsonDeserializer<String> {

        @Override
        public String deserialize(JsonParser parser, DeserializationContext context)
                throws IOException, JsonProcessingException {
            final TreeNode treeNode = parser.getCodec().readTree(parser);
            if (treeNode.isArray()) {
                final ArrayNode arrayNode = (ArrayNode) treeNode;
                return StreamSupport.stream(arrayNode.spliterator(), false)
                        .map(node -> node.asText(""))
                        .filter(StringUtils::hasText)
                        .collect(Collectors.joining(","));
            }
            return "";
        }
    }

}
